<?php
namespace App\Http\Controllers\Dashboard;

use App\Jobs\ImportLoan;
use App\Models\LoanCreditProvident;
use App\Models\LoanGeneral;
use App\Models\LoanMortgageCar;
use App\Models\LoanMortgageHouse;
use App\Models\LoanMortgageTax;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\UploadedFile;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use OpenSpout\Common\Exception\InvalidArgumentException;
use OpenSpout\Common\Exception\IOException;
use OpenSpout\Common\Exception\UnsupportedTypeException;
use OpenSpout\Writer\Exception\WriterNotOpenedException;
use Rap2hpoutre\FastExcel\Facades\FastExcel;
use Symfony\Component\HttpFoundation\StreamedResponse;

class ImportController extends BaseController
{

    /**
     * 模版下载
     *
     * @param Request $request
     * @param $category
     * @return string|StreamedResponse
     * @throws IOException
     * @throws InvalidArgumentException
     * @throws UnsupportedTypeException
     * @throws WriterNotOpenedException
     */
    public function loanTemplate(Request $request, $category) {
        if (!in_array($category, ['general', 'credit-provident', 'mortgage-car', 'mortgage-house', 'mortgage-tax'])) {
            return response()->json([
                'code' => 1,
                'msg' => '无效贷款类型',
                'data' => null
            ]);
        }

        if ($category == 'credit-provident') {
            $header = LoanCreditProvident::TEMPLATE_HEADER;
            $title = "公积金信用贷";
        } elseif ($category == 'mortgage-car') {
            $header = LoanMortgageCar::TEMPLATE_HEADER;
            $title = "车辆抵押贷";
        } elseif ($category == 'mortgage-house') {
            $header = LoanMortgageHouse::TEMPLATE_HEADER;
            $title = "房屋抵押贷";
        } else if ($category == 'mortgage-tax') {
            $header = LoanMortgageTax::TEMPLATE_HEADER;
            $title = "企业税贷";
        } else {
            $header = LoanGeneral::TEMPLATE_HEADER;
            $title = "银行综合贷款";
        }

        $data = array_fill_keys(array_values($header), '');
        foreach ($data as $k => &$v) {
            if (str_contains($k, "时间") || str_contains($k, "日期")) {
                $v = date("Y-m-d H:i:s");
            }
        }

        return FastExcel::data([$data])
          ->download(sprintf("%s模版_%s.xlsx", $title, date("dHis")));
    }

    /**
     * 上传文件
     *
     * @param Request $request
     * @return JsonResponse
     */
    public  function upload(Request $request) {

        /* @var UploadedFile $file  */
        $file = $request->file('file');

        $path = Storage::putFileAs(
            sprintf('import/%s', date("Ymd")),
            $file,
            sprintf("%s.%s", md5($file->getFilename() . rand()), $file->guessExtension())
        );

        return response()->json([
            'code' => 0,
            'msg' => '上传成功',
            'data' => $path
        ]);
    }

    /**
     * 解析模版文件
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function parse(Request $request) {

        $path = Storage::path( $request->file);
        if (!is_file($path)) {
            return response()->json([
                'code' => 1,
                'msg' => '文件不存在: ' . $request->file,
                'data' => null
            ]);
        }

        $data = FastExcel::import($path);

        $header = $data->count() >= 1 ? array_keys(current($data->take(1)->toArray())) : [];

        $items = [];
        foreach ($data->take(40) as $row) {
            foreach ($row as $k => &$v) {
                if (str_contains($k, "时间") || str_contains($k, "日期")) {
                    $time = strtotime($v);
                    $v = $time ? date("Y-m-d H:i:s", $time) : '-';
                }
            }
            $items[] = $row;
        }

        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => [
                'headers' => $header,
                'total' => $data->count(),
                'items' => $items
            ]
        ]);
    }

    /**
     * 保存数据到数据库
     * @param Request $request
     * @return JsonResponse
     */
    public function save(Request $request, $category) {

        if (!in_array($category, ['general', 'credit-provident', 'mortgage-car', 'mortgage-house', 'mortgage-tax'])) {
            return response()->json([
                'code' => 1,
                'msg' => '无效贷款类型',
                'data' => null
            ]);
        }

        $path = Storage::path($request->file);
        if (!is_file($path)) {
            return response()->json([
                'code' => 1,
                'msg' => '文件不存在: ' . $request->file,
                'data' => null
            ]);
        }

        ImportLoan::dispatch($request->file, $category, $request->user()->id);

        return response()->json([
            'code' => 0,
            'msg' => '请求成功',
            'data' => [
                'key' => md5($request->file)
            ]
        ]);
    }

    /**
     * 处理进度
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function progress(Request $request) {
        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => Cache::get($request->key,  ['total' =>0, 'success'=> 0, 'fail' => 0, 'progress'=> 0, 'duplicate' => 0])
        ]);
    }
}
